package com.blog.service.impl;

import com.blog.mapper.HobbyMapper;
import com.blog.pojo.Hobby;
import com.blog.pojo.Tag;
import com.blog.service.HobbyService;
import com.blog.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HobbyServiceImpl implements HobbyService {

    @Autowired
    private HobbyMapper hobbyMapper;

    // 查看当前用户兴趣标签
    @Override
    public List<Tag> listByCurrentUser() {
        Integer userId = Integer.parseInt(UserContext.getUserId());
        return hobbyMapper.listByUserId(userId);
    }

    // 查看用户兴趣标签
    @Override
    public List<Tag> listByUserId(Integer id) {
        return hobbyMapper.listByUserId(id);
    }

    // 当前用户批量添加感兴趣的标签
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(List<Integer> tagIds) {
        Integer userId = Integer.parseInt(UserContext.getUserId());
        for(Integer tagId: tagIds) {
            if(hobbyMapper.find(userId,tagId) == 0) {
                Hobby hobby = new Hobby();
                hobby.setUserId(userId);
                hobby.setTagId(tagId);
                hobbyMapper.insert(hobby);
            }
        }
    }

    // 当前用户删除感兴趣的标签
    @Override
    public void delete(Integer tagId) {
        Integer userId = Integer.parseInt(UserContext.getUserId());
        hobbyMapper.delete(userId, tagId);
    }

}
